﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Drawing;
using System;
using System.Threading.Tasks;
using Xiao.Application.Services.User;
using static Cx.NetCoreUtils.Filters.GlobalModelStateValidationFilter;
using Xiao.Code.DbEnum;
using Xiao.Util;
using Cx.NetCoreUtils.Extensions;

namespace Xiao.Web.Controllers
{
    /// <summary>
    /// 登录模块
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly IRedisUtil _redisUtil;
        private readonly IConsumerService _consumerService;
        public LoginController(
            IRedisUtil redisUtil,
            IConsumerService consumerService)
        {
            _redisUtil = redisUtil;
             _consumerService = consumerService;
        }
        /// <summary>
        /// 登录账号
        /// </summary>
        /// <param name="user"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(string user,string pass)
        {
            var userData=await _consumerService.GetConsumer(user, pass);
            if (userData.Status != StatusEnum.Start) return new ModelStateResult("账号状态异常");
            var token = StringUtil.GetString(124);
            await _redisUtil.SetAsync(token, userData, DateTime.Now.AddMinutes(30));
            return new OkObjectResult(new { token, user = userData });
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Exit()
        {
            var token = HttpContext.Request.Headers["Authorization"].ToString();
            await _redisUtil.DetleteAsync(token);
            return new OkObjectResult("退出登录成功");
        }

        /// <summary>
        /// 刷新token过期时间
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Refresh()
        {
            var token = HttpContext.Request.Headers["Authorization"].ToString();
            await _redisUtil.SetDateAsync(token, DateTime.Now.AddMinutes(30));
            return new OkObjectResult("刷新成功");
        }
    }
}
